"""
    Created by 范钟<coder.zf@outlook.com> on 2019/04/06
"""

from flask import render_template, request, flash

from . import web
from forms.book import SearchForm
from helper.search import is_isbn
from spider.yushu_book import YuShuBook
from view_models.book import BookCollection, BookViewModel


@web.route('/book/search/')
def search():
    """
    q：普通关键字 isbn
    page: 分页
    :return:
    """
    books = BookCollection()
    yushu_book = YuShuBook()

    form = SearchForm(request.args)
    if not form.validate():
        flash("请输入书籍名称")
        return render_template("search_result.html", books=books)

    q = form.q.data.strip()
    page = form.page.data

    if is_isbn(q):
        yushu_book.search_by_isbn(q)
    else:
        yushu_book.search_by_keyword(q, page)

    books.fill(yushu_book, q)
    return render_template("search_result.html", books=books)


# 书籍详情页面
@web.route("/book/<isbn>/detail")
def book_detail(isbn):
    yushu_book = YuShuBook()
    yushu_book.search_by_isbn(isbn)
    book = BookViewModel(yushu_book.first)
    return render_template("book_detail.html", book=book, wishes=[], gifts=[])


@web.route("/save_to_wish")
def save_to_wish():
    pass
